package com.trace.meat.controller;

import com.trace.meat.entity.AdminAcct;
import com.trace.meat.entity.Ent;
import com.trace.meat.entity.Lic;
import com.trace.meat.entity.Result;
import com.trace.meat.entityModel.LicModel;
import com.trace.meat.service.AdminAcctService;
import com.trace.meat.service.EntService;
import com.trace.meat.service.LicService;
import com.trace.meat.service.TypeTblService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.relational.core.sql.In;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//http://127.0.0.1:11451/adminAcct/selectOne/1
//http://127.0.0.1:11451/adminAcct/selectOne?id=1
//http://127.0.0.1:11451/adminAcct/selectLine?offset=0&limit=3
//http://127.0.0.1:11451/adminAcct/insertOne?id=6&username=lkj&pwd=123
//http://127.0.0.1:11451/adminAcct/deleteOne?id=4
//http://127.0.0.1:11451/adminAcct/updateOne?id=5&username=khhj&pwd=12hh

/**
 * (AdminAcct)表控制层
 *管理员账号
 * @author makejava
 * @since 2021-06-19 11:17:23
 */
@CrossOrigin
@RestController
@RequestMapping("admin")
public class AdminAcctController {
    /**
     * 服务对象
     */
    @Resource
    private AdminAcctService adminAcctService;
    @Resource
    private LicService licService;
    @Resource
    private EntService entService;
    @Resource
    private TypeTblService typeTblService;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    public AdminAcct selectOne(Integer id) {
        return this.adminAcctService.queryById(id);
    }
    /**
     * 查询指定行数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    public List<AdminAcct> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit) {
        return this.adminAcctService.queryAllByLimit(offset, limit);
    }
    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public boolean deleteById(Integer id) {
        return this.adminAcctService.deleteById(id);
    }
    /**
     * 修改数据
     */
    public AdminAcct update(Integer id,String username,String pwd) {
        AdminAcct adminAcct=new AdminAcct();
        adminAcct.setId(id);
        adminAcct.setUsername(username);
        adminAcct.setPwd(pwd);
        return this.adminAcctService.update(adminAcct);
    }
    //登录注册
    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return Result对象
     */
    @GetMapping( "login")
    public Result login(String username, String password) {
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        Result result=new Result();
        result.setSuccess(false);
        result.setDetail(null);
        if (username==null||username=="")
        {
            result.setMsg("用户名不可为空");
            System.out.println("用户名不可为空");
            return result;
        }
        if(password==""||password==null)
        {
            result.setMsg("密码不可为空");
            System.out.println("密码不可为空");
            return result;

        }
        AdminAcct temp=new AdminAcct();
        temp=this.adminAcctService.queryByUserName(username);
        if(temp==null) {
            System.out.println("用户名不存在");
            result.setMsg("用户名不存在");
            return result;
        }
        boolean flag=bCryptPasswordEncoder.matches(password,temp.getPwd());
        if(flag)
        {
            temp.setPwd("");
            System.out.println("登录成功");
            result.setMsg("登录成功");
            result.setSuccess(true);
            if(temp.getToken()==null)
            {
                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                temp.setToken(uuid);
                this.adminAcctService.update(temp);
            }
            result.setDetail(temp);
            return result;
        }
        else
        {
            result.setMsg("密码错误");
            System.out.println("密码错误");
            return result;
        }
    }
    /**
     * 注册
     *
     * @param username 用户名
     * @param password 密码
     * @return Result对象
     */
    @PostMapping("register")
    public Result register(String username,String password) {
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        Result result=new Result();
        AdminAcct temp=new AdminAcct();
        result.setSuccess(false);
        result.setDetail(null);
        temp=this.adminAcctService.queryByUserName(username);
        if (username==null||username=="")
        {
            result.setMsg("用户名不可为空");
            System.out.println("用户名不可为空");
            return result;
        }
        if (temp!=null)
        {
            result.setMsg("用户名重复");
            System.out.println("用户名重复");
            return result;
        }
        temp=new AdminAcct();
        temp.setUsername(username);
        password=bCryptPasswordEncoder.encode(password);
        temp.setPwd(password);
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        temp.setToken(uuid);
        this.adminAcctService.insert(temp);
        temp.setPwd("");
        result.setDetail(temp);
        result.setMsg("注册成功");
        result.setSuccess(true);
        System.out.println("注册成功");
        return result;
    }
    //备案审核相关
    /**
     * 输出待审核列表
     * @param id 主键
     * @return
     */
    public Result licOfAudit_list(Integer id){
        Result result=new Result();
        result.setSuccess(false);
        if(adminAcctService.queryById(id)==null){
            result.setMsg("企业id错误");
            return result;
        }
        result.setDetail(licService.getModelByState(0));
        result.setSuccess(true);
        result.setMsg("待审核证书获取成功");
        return result;
    }
    /**
     *
     * @param lid
     * @param state
     * @return
     */
    /**
     * 审核证书
     * @param lid 证书id
     * @param state 证书状态
     * @return
     */
    @PostMapping("setLicState")
    public Result SetLicState(Integer lid,Integer state){
        Result result=new Result();
        result.setSuccess(false);
        if(lid==null){
            result.setMsg("lid不可为空");
            return result;
        }
        Lic lic=licService.queryById(lid);
        if(lic==null){
            result.setMsg("证书id错误");
            return result;
        }
        result.setSuccess(true);
        result.setMsg("证书通过成功");
        lic.setLicState(state);
        result.setDetail(licService.update(lic));
        return result;
    }
    /**
     * 证书筛选
     * @param ename 企业名
     * @param lictype 证书类型
     * @param sernum 编号
     * @return
     */
    @Transactional(readOnly = true)
    @GetMapping("licList")
    public Result Lic_Screen(String ename, Integer lictype, String sernum,Integer licstate){
        Result result=new Result();
        result.setSuccess(false);
        List<Ent> list=new ArrayList<Ent>();
        if(ename!=null){
            list=entService.queryByEName(ename);
        if(list.isEmpty()){
            result.setMsg("无该企业名的类似企业");
            System.out.println("企业名错误");
            return result;
        }
        }
        if (lictype!=null&&typeTblService.queryById(lictype)==null){
            result.setMsg("企业类型错误");
            System.out.println("企业类型错误");
            return result;
        }
        List<LicModel> list_lic=new ArrayList<LicModel>();
        if(!list.isEmpty()){
            Iterator<Ent> iterator=list.listIterator();
        while (iterator.hasNext()) {
            Lic lic = new Lic();
            lic.setEid(((Ent)iterator.next()).getEid());
            lic.setLicType(lictype);
            lic.setSerNum(sernum);
            lic.setLicState(licstate);
            List<LicModel> temp=licService.queryAllModel(lic);
            list_lic.addAll(temp);
        }
        }
        else {
            Lic lic = new Lic();
            lic.setLicType(lictype);
            lic.setSerNum(sernum);
            lic.setLicState(licstate);
            list_lic=licService.queryAllModel(lic);
        }
        if(list_lic.isEmpty()){
            result.setMsg("无此类证书");
            return result;
        }
        result.setMsg("筛选成功");
        result.setSuccess(true);
        result.setDetail(list_lic);
        return result;
    }

    /**
     * 删除证书
     * @param lid 证书编号
     * @return Result
     */
    @PostMapping("licdelete")
    public Result Lic_Delete(Integer lid){
        Result result=new Result();
        result.setSuccess(false);

        if(licService.deleteById(lid)) {
            result.setSuccess(true);
            result.setMsg("删除成功");
            return result;
        }
        else {
            result.setMsg("删除失败，证书不存在");
            return result;
        }
    }
    /**@PostMapping("")
    public Result lic_Pass(Integer lid){
        Result result=new Result();
        result.setSuccess(false);
        Lic lic=licService.queryById(lid);
        if(lic==null){
            result.setMsg("证书id错误");
            return result;
        }
        result.setSuccess(true);
        result.setMsg("证书通过成功");
        lic.setLicState((short)1);
        result.setDetail(licService.update(lic));
        return result;
    }
    @PostMapping("LicNoPass")
    public Result lic_NoPass(Integer lid){
        Result result=new Result();
        result.setSuccess(false);
        Lic lic=licService.queryById(lid);
        if(lic==null){
            result.setMsg("证书id错误");
            return result;
        }
        result.setSuccess(true);
        result.setMsg("证书不通过成功");
        lic.setLicState((short)2);
        result.setDetail(licService.update(lic));
        return result;
    }
     */
    //企业信息相关
    /**
     * 企业信息筛选
     * @param username 用户名
     * @param ename 企业名
     * @param etype 企业类型
     * @param tel 电话
     * @param email 邮箱
     * @return
     */
    @GetMapping("userList")
    public Result Account_Screen(String username,String ename,Integer etype,String tel,String email){
        Result result=new Result();
        result.setSuccess(false);
        String regEx = "^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4})*$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher ;
        /**if(email!=null) {
            //邮箱格式验证
            matcher=pattern.matcher(email);
            if (!matcher.matches()) {
                result.setMsg("邮箱格式错误");
                System.out.println("邮箱格式错误");
                return result;
            }
        }*/
        //用户名格式验证
        /**regEx="-^[\\w\\d_]{4,16}$";
        pattern=Pattern.compile(regEx);
        if(username!=null){
            matcher=pattern.matcher(username);
            if(!matcher.matches()){
            result.setMsg("用户名格式错误");
            System.out.println("用户名格式错误");
            return result;
            }
        }*/
        if (etype!=null&&typeTblService.queryById(etype)==null){
            result.setMsg("企业类型错误");
            System.out.println("企业类型错误");
            return result;
        }
        Ent ent=new Ent();
        ent.setTel(tel);
        ent.setUsername(username);
        ent.setEname(ename);
        ent.setEmail(email);
        ent.setEtype(etype);
        List list=entService.queryAll(ent);
        if (list.isEmpty()){
            result.setMsg("无此类信息");
            return result;
        }
        result.setDetail(entService.queryAll(ent));
        result.setSuccess(true);
        result.setMsg("筛选成功");
        return result;
    }
    /**
     * 修改企业信息
     * @param eid 企业id
     * @param etype 企业类型
     * @param tele 电话
     * @param ename 企业名字
     * @param email 邮箱
     * @return
     */
    @PostMapping("editEntDetail")
    public Result EditEnt(Integer eid,Integer etype,String tele,String ename,String email){
        //邮箱格式验证
        Result result=new Result();
        result.setSuccess(false);
        String regEx="^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4})*$";
        Pattern pattern=Pattern.compile(regEx);
        Matcher matcher;
        if(email!=null) {
            matcher=pattern.matcher(email);
            if (!matcher.matches()) {
                result.setMsg("邮箱格式错误");
                System.out.println("邮箱格式错误");
                return result;
            }
        }
        Ent ent=new Ent();
        ent.setEid(eid);
        ent.setEtype(etype);
        ent.setTel(tele);
        ent.setEname(ename);
        result.setSuccess(true);
        result.setMsg("修改成功");
        ent=entService.update(ent);
        ent.setPwd("");
        result.setDetail(ent);
        return result;
    }
    /**
     *重置企业账号token
     * @param eid 企业id
     * @return
     */
    @PostMapping("resetEntToken")
    public Result ResetEntToken(Integer eid){
        Result result=new Result();
        result.setSuccess(false);
        if(eid==null){
            result.setMsg("eid不可为空");
            return result;
        }
        if(entService.queryById(eid)==null){
            result.setMsg("eid错误");
            return result;
        }
        Ent ent=entService.queryById(eid);
        String token=UUID.randomUUID().toString().replaceAll("-","");
        ent.setToken(token);
        ent=entService.update(ent);
        result.setMsg("重置token成功");
        result.setSuccess(true);
        result.setDetail(ent);
        return result;
    }

}
